package com.tanhua.server.service;



import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;

import com.tanhua.dubbo.api.PBVoiceApi;
import com.tanhua.dubbo.api.UserInfoApi;

import com.tanhua.dubbo.api.VoiceFunctionApi;
import com.tanhua.model.domain.UserInfo;

import com.tanhua.model.mongo.VoiceCount;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.VoiceVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;


/**
 * @Author ${南五磊}
 * @Date 2022/1/14 15:20
 */
@Service
public class TaoHuaService {
    @DubboReference
    private PBVoiceApi pbVoiceApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private FastFileStorageClient client;

    @DubboReference
    private VoiceFunctionApi voiceFunctionApi;

    /**
     * 桃花传音-发送语音
     *
     * @param soundFile
     */
    public void sendVoice(MultipartFile soundFile) throws IOException {
        Long userId = UserHolder.getUserId();
        //判断是否有限定次数表
        VoiceCount voiceCount = voiceFunctionApi.findByUserId(Integer.valueOf(userId.toString()));
        //用户第一次使用就创建表
        if (voiceCount == null) {
            voiceCount = new VoiceCount();
            voiceCount.setSendCount(3);
            voiceCount.setUserId(userId.intValue());
            voiceFunctionApi.saveVoiceCount(voiceCount);
        }
        //查询是否还有发送次数
        if (voiceCount.getSendCount() == 0) {
            throw new BusinessException(ErrorResult.sentError());
        }
        //1.1获取文件后缀
        String suffix = soundFile.getOriginalFilename()
                .substring(soundFile.getOriginalFilename().lastIndexOf(".") + 1);
        //1.2上传文件
        StorePath storePath = client.uploadFile(soundFile.getInputStream(), soundFile.getSize(), suffix, null);
        //1.3获取文件路径
        String voiceUrl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();
        //获取自身性别
        UserInfo userinfo = userInfoApi.findById(userId);
        String gender = userinfo.getGender();
        Integer age = userinfo.getAge();
        //2.调用服务保存音频记录
        pbVoiceApi.saveVoice(voiceUrl, age, gender, userId);
        //3.更新发送次数-更新接收次数
        voiceFunctionApi.updateSendCount(voiceCount);
    }

    /**
     * 接收语音
     *
     * @return
     */
    public ResponseEntity receiveVoice(){
        //当前id
        Long userId = UserHolder.getUserId();

        //判断是否有限定次数表
        VoiceCount voiceCount = voiceFunctionApi.findByUserId(Integer.valueOf(userId.toString()));
        //用户第一次使用就创建表
        if (voiceCount == null) {
            voiceCount = new VoiceCount();
            voiceCount.setReceiveCount(3);
            voiceCount.setUserId(userId.intValue());
            voiceFunctionApi.saveVoiceCount(voiceCount);
        }
        //查询是否还有接收次数
        if (voiceCount.getReceiveCount() == 0) {
            throw new BusinessException(ErrorResult.voiceError());
        }
        //根据id查询当前前用户基本信息（需要性别，年龄,地址的数据类型不能序列化，在实现类取）
        UserInfo userInfo = userInfoApi.findById(userId);

        //查询已接收的音频的主键id
        List<ObjectId> objectIdList = voiceFunctionApi.findVoiceUseId(userId.intValue());
        //性别、年龄、id、接收过的主键id
        VoiceVo VoiceVo = pbVoiceApi.findPBVoice(userInfo.getGender(), userInfo.getAge(), userId, objectIdList);
        if (VoiceVo==null){
            throw new BusinessException(ErrorResult.outVoiceError());
        }
        //查询被接收用户基本信息
        UserInfo info = userInfoApi.findById(VoiceVo.getId().longValue());
        //被接收用户昵称
        VoiceVo.setNickName(info.getNickname());
        //被接收用户头像
        VoiceVo.setAvatar(info.getAvatar());
        //更新接收次数
        voiceFunctionApi.updateReceiveCount(voiceCount);
        VoiceVo.setRemainingTimes(voiceCount.getReceiveCount()-1);
        //返回
        return ResponseEntity.ok(VoiceVo);
    }
}
